//
//  testRegex.m
//  parser
//
//  Created by Daniel Braun on 04/05/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "DBRegex.h"
#import "DBLexer.h"
#import "DBParser.h"
//#import "DBParserAstGen.h"

static BOOL err=NO;
static void testMatch(DBRegex *re, NSString *s, BOOL expv)
{
	BOOL m=[re matchInString:s];
	NSLog(@"match %@ in %@\n", m ? @"YES":@"no", s);
	if (m!=expv) {
		NSLog(@"*** NOT OK **\n");
		err=YES;
	}
}

int main(int argc, char *argv[])
{
	NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];
	
	DBRegex *re=[DBRegex regexWithPattern:@"a[1-9]*z"];
	testMatch(re, @"coucou ceci est a1233424z troll", YES);
	testMatch(re, @"coucou ceci est a1233e424z troll", NO);
	testMatch(re, @"coucou ceci est az troll", YES);
	testMatch(re, @"coucou ceci est A324 troll", NO);

	[pool release];
	if (err) return 1;
	
	pool=[[NSAutoreleasePool alloc]init];

#define TOK_ID	1
#define TOK_NUM 2
#define TOK_ADDOP	3
#define TOK_MULTOP	4

	DBLexer *lexer=[[DBLexer alloc]init];
 	[lexer autorelease];
	[lexer addToken:@"coucou" value:TOK_ID  ast:@"$"];
	[lexer addToken:@"troll" value:TOK_ID ast:@"$"];
	[lexer addToken:@"bus" value:TOK_ID ast:@"$"];
	
	[lexer addToken:[NSCharacterSet characterSetWithCharactersInString:@" \t\n\r"] value:-1];
	[lexer addToken:[DBRegex regexWithPattern:@"[0-9][0-9]*"] value:TOK_NUM ast:@"$"];
	[lexer addToken:[DBRegex regexWithPattern:@"[+-]"] value:TOK_ADDOP ast:@"LR"];
	[lexer addToken:[DBRegex regexWithPattern:@"[\\*/]"] value:TOK_MULTOP  ast:@"LR"];

	NSArray *tokens=[lexer parseString:@"coucou+34+3/\t983   troll   "];
	NSLog(@"parsed : %@\n", tokens);

	
	DBParser *parser=[[DBParser alloc]init];
	[parser autorelease];
	/*
	 expr  ::= multexpr ( addop multexpr )*;
	 multexpr ::= expr1 (multop expr1)*
	 expr1 ::= num | id
	 */
	DBParserRule *expr1=[DBParserRuleNamed ruleNamed:@"expr1" action:(SEL)0 rule:
		[DBParserRuleChoice choice:
			[DBParserRuleTerminal terminalRule:TOK_NUM action:(SEL)0],
			[DBParserRuleTerminal terminalRule:TOK_ID action:(SEL)0], nil], nil];
	DBParserRule *multexpr=[DBParserRuleNamed ruleNamed:@"multexpr" action:(SEL)0 rule:
		expr1, [ DBParserRuleOptional optionalMany:
			[DBParserRuleTerminal terminalRule:TOK_MULTOP action:(SEL)0],
		expr1,nil],nil];
	DBParserRule *expr=[DBParserRuleNamed ruleNamed:@"expr" action:(SEL)0 rule:
		multexpr, [ DBParserRuleOptional optionalMany:
			[DBParserRuleTerminal terminalRule:TOK_ADDOP action:(SEL)0],
			multexpr,nil],nil];
	[parser setRule:expr];
	//DBParserAstGen *astGen=[[DBParserAstGen alloc]init];
	//[parser setTarget:astGen];
	//[parser parseTokens:[lexer parseString:@"2 + troll *3+8*5+7"]];
	[parser parseTokens:[lexer parseString:@"2 + 3"]];

	id ast=[parser ast];
	NSLog(@"got ast %@\n", ast);
	[pool release];
	if (err) return 1;
	return 0;
}